<?php
/**
 * Created by PhpStorm.
 * User: xiong <1099446868@qq.com>
 * DateTime: 2018/10/31
 * TIME: 13:42
 */

namespace app\index\controller;


use app\index\model\User as UserModel;
use app\index\validate\RegisterValidate;
use app\index\validate\UserSignValidate;
use think\Db;
use think\facade\Cookie;
use think\facade\Request;


class User extends BaseController {

    protected $beforeActionList = [
        'islogin'=>['except'=>'login,sign,register']
    ];


    //用户登录
    public function login(){

        return $this->fetch('login3');
    }

    public function sign(){
        //数据验证
        //$error = (new UserSignValidate())->goCheck();
        $request = Request::instance();
        $data = $request->param();

        $return = [
            'code' => 200,
        ];
        //当ajax提交数据中含有表单令牌时，验证令牌暂时不可以在验证层验证，只能在控制器层验证，否则token不通过
        $error = (new UserSignValidate())->gocheck();
        if($error['istrue'] === false){
            $return['code'] = 400;
            $return['msg'] = $error['msg'];
        }

        $phone = UserModel::phone_email_login($data['phone_email']);
        if($phone == false){
            $return['code'] = 400;
            $return['msg']['phone_email'] = '请输入正确的手机号或邮箱';
        }

        if($return['code'] == 400){
            $return['token']=Request::token();
            return json($return);
        }

        //登录验证
        $login = UserModel::login($data, $phone);
        $login['token'] = Request::token();
        return json($login);
    }

    public function register(){
        return $this->fetch('register3');
    }

    public function adduser(){
        $request = Request::instance();
        $data = $request->param();
        $return = [
            'code' => 200,
        ];

        $error = (new RegisterValidate())->goCheck();
        if($error['istrue'] === false){
            $return['code'] = 400;
            $return['msg'] = $error['msg'];
        }

        //根据表单参数不同，返回值有5种情况 false/phone1/email1...
        $isphone = UserModel::phone_email($data['phone_email']);
        if($isphone === false){
            $return['code'] = 400;
            $return['msg']['phone_email'] = '请输入正确的用户名手机号或者邮箱!';
        }else if($isphone == 'phone_exist' || $isphone == 'email_exist'){
            $return['code'] = 400;
            $return['msg']['phone_email'] = '您输入的邮箱或者手机号已经被注册!';
        }

        if($return['code'] == 400){
            $return['token']=Request::token();
            return json($return);
        }

        //上面三个if都不满足，插入数据
        $err = UserModel::register($data, $isphone);
        $err['token'] = Request::token();
        return json($err);
    }

    public function logout(){
        Cookie::set('username','',-1);
        //Session::set('username', '', -1);
        $this->redirect('index/index');
    }
}